package cn.itcast.star.graph.core.service.impl;

import cn.itcast.star.graph.comfyui.client.pojo.ComfyuiTask;
import cn.itcast.star.graph.core.service.RedisService;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author Windows
 */
@Service
public class RedisServiceImpl implements RedisService {
    private final static String TASK_KEY_PREFIX = "task_";
    private final static String DISTRIBUTED_ID_KEY = "DISTRIBUTED_ID";
    private final static String DISTRIBUTED_QUEUE_KEY = "DISTRIBUTED_QUEUE";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 将数据模板存入redis中
     * @param comfyuiTask
     * @return
     */
    @Override
    public ComfyuiTask addQueueTask(ComfyuiTask comfyuiTask) {
        Long index =stringRedisTemplate.opsForValue().increment(DISTRIBUTED_ID_KEY);
        comfyuiTask.setIndex(index);
        //添加任务数据【维护一个任务队列】
        stringRedisTemplate.opsForValue().set(String.format("%s%s",TASK_KEY_PREFIX,comfyuiTask.getId()),
                JSON.toJSONString(comfyuiTask));
        //压入队列【要求处理某个任务队列数据时，从这个里面取数据】
        stringRedisTemplate.opsForZSet().add(DISTRIBUTED_QUEUE_KEY,comfyuiTask.getId(),index);
        return comfyuiTask;
    }
}
